package com.beone.admin.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.base.common.beans.Result;
import com.base.common.enums.ResultCodeEnum;
import com.base.common.util.algorithm.DigestUtils;
import com.beone.admin.controller.app.common.BaseAppController;
import com.beone.admin.controller.base.BaseUserController;
import com.beone.admin.controller.common.ControllerUtils;
import com.beone.admin.entity.BaseUser;
import com.beone.admin.service.BaseUserService;
import com.beone.admin.utils.TokenUtils;
import com.beone.admin.utils.UuidUniqueKeyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

/**
 * <p>
 * 用户相关 控制器
 * </p>
 *
 * @author Pagenny
 * @date 2019-05-19 11:03
 **/
@Api(value = "APP端用户相关", tags = {"APP端"})
@RestController("/appUserController")
@RequestMapping("/api/user")
public class UserController extends BaseAppController {

    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private BaseUserService baseUserService;

    @ApiOperation("登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号", dataType = "string", paramType = "query",required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "string", paramType = "query",required = true),
    })
    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public Result login(String account, String password) {
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            return Result.failure("缺少参数");
        }
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("user_account", account);
        BaseUser user = baseUserService.selectOne(wrapper);
        if (user != null) {
            String pwd = DigestUtils.md5(password);
            if (user.getUserPwd().equals(pwd)) {
                String token = UuidUniqueKeyUtil.uuid();
                tokenUtils.setUserToken(String.valueOf(user.getUserId()), token);
                return Result.success("登录成功", token);
            }
        }
        return Result.failure("用户名或密码不正确");
    }

    @ApiOperation("注销")
    @RequestMapping(value = "/logout", method = {RequestMethod.GET, RequestMethod.POST})
    public Result logout(HttpServletRequest request) {
        String token = tokenUtils.getTokenFromReq(request);
        tokenUtils.removeToken(token);
        return Result.success();
    }

    @ApiOperation(value = "修改用户密码", notes = "根据用户Id修改用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "旧密码", required = true
                    , paramType = "param", dataType = "string"),
            @ApiImplicitParam(name = "newPassword1", value = "新密码1", required = true
                    , paramType = "param", dataType = "string"),
            @ApiImplicitParam(name = "newPassword2", value = "新密码2", required = true
                    , paramType = "param", dataType = "string"),
    })
    @PostMapping(value = "/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword1, String newPassword2) {
        if (!Pattern.matches(BaseUserController.PWD_REG, newPassword1)
                || !Pattern.matches(BaseUserController.PWD_REG, newPassword2)) {
            return Result.failure("密码必须是6-12位字母(区分大小写)和数字的组合");
        }
        if (!newPassword1.equals(newPassword2)) {
            return Result.failure("两次输入的新密码不一致");
        }
        if (oldPassword.equals(newPassword1)) {
            return Result.failure("新密码不能与原始密码相同");
        }
        JSONObject jsonObject = baseUserService.updatePwd(oldPassword, newPassword1, getUserId());
        return covertResult(jsonObject);
    }

    @ApiOperation("用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号", dataType = "string", paramType = "query",required = true),
    })
    @RequestMapping(value = "/userInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public Object noToken(String account) {
        return baseUserService.loadUserByUsername(account);
    }

    @ApiIgnore
    @RequestMapping(value="/noToken")
    public Result<String> noToken() {
        return Result.failure("参数中没有找到token信息");
    }

    @ApiIgnore
    @RequestMapping(value="/noLogin")
    public Result<String> noLogin() {
        return Result.build(ResultCodeEnum.TOKEN_ERROR,"用户信息已过期，请重新登录",null);
    }
}
